# -*- coding: UTF-8 -*-
'''
Created on 27.06.2014

@author: MathiasAr
'''
import sys
import Image
import gtkImageAppBase
import ImageHelper
from ImagePuzzle import imagePuzzle

try:
    import pygtk
    pygtk.require("2.0")
except:
    pass
try:
    import gtk
    import gtk.glade
except:
    sys.exit(1)

class GtkImagePuzzle(gtkImageAppBase.GtkImageAppBase):
    
    def __init__(self):
        # initialize base application
        gtkImageAppBase.GtkImageAppBase.__init__(self)
        
        # load glade XML
        xml = gtk.glade.XML('gtkImagePuzzle.glade', 'scrolledwindow1')
        
        self._filechooser = xml.get_widget('filechooserbutton1')
        self._labelDimensions = xml.get_widget('label3')
        self._labelResultDim = xml.get_widget('label9')
        self._puzzleSize = xml.get_widget('spinbutton1')
        self._tileSize = xml.get_widget('spinbutton2')
        self._noDouble = xml.get_widget('checkbutton1')
        self._start = xml.get_widget('button1')
        self._labelStatus = xml.get_widget('label6')
        self._previewImage = xml.get_widget('image1')
        self._save = xml.get_widget('button2')
        
        # preset attributes
        self._fileFilter = gtk.FileFilter()
        self._fileFilter.add_pattern('*.jpg')
        self._fileFilter.add_pattern('*.png')
        self._fileFilter.add_pattern('*.jpeg')
        self._fileFilter.add_pattern('*.bmp')
        self._fileFilter.add_pattern('*.gif')
        self._fileFilter.add_pattern('*.tif')
        self._filechooser.set_filter(self._fileFilter)
        self._labelStatus.set_text('')
        
        # append callbacks
        self._filechooser.connect('file-set', self.onFileSet)
        self._filechooser.connect('selection-changed', self.onFileSet)
        self._start.connect('clicked', self.onStart)
        self._save.connect('clicked', self.onSave)
        
        # append to base container
        self.append(xml.get_widget('scrolledwindow1'), gtk.Label("Puzzle"))
        
        # initialize internal states
        self._running = False
        
    
    def onFileSet(self, widget):
        self._imageFileName = self._filechooser.get_filename().decode()
        self._im = Image.open(self._imageFileName, 'r')
        self._im = ImageHelper.AutoOrientImage(self._im, ImageHelper.GetImageOrientation(self._imageFileName))
        self._labelDimensions.set_text("%i x %i" % self._im.size)
        self._labelResultDim.set_text("0 x 0")
        self._previewImage.clear()
        size = min(self._im.size)
        self._tileSize.set_range(1, max(1, int(size / 4)))
        if (self._tileSize.get_value() <= 1):
            self._tileSize.set_value(10)
        if (self._puzzleSize.get_value() <= 0):
            self._puzzleSize.set_value(20)
        
        # set preview
        im = Image.open(self._imageFileName, 'r')
        im = ImageHelper.AutoOrientImage(im, ImageHelper.GetImageOrientation(self._imageFileName))
        im.thumbnail((320, 240))
        pixbuf = ImageHelper.GetGtkPixbuf(im)
        self._previewImage.set_from_pixbuf(pixbuf)
        pass
    
    def onStart(self, widget):
        if self._running:
            self._running = False
            return
        
        # check parameter
        fileName = self._filechooser.get_filename()
        if fileName != self._imageFileName:
            self.onStart(widget)
        files = self.getFiles()
        if (len(files) <= 0):
            return
        
        # lock
        self._running = True
        self._start.set_label('Cancel')
        self._resultIm = None
        
        # define callback method
        def _updateCall(self, percent):
            self._labelStatus.set_text('Processing: %i %%' % int(percent))
            gtk.main_iteration()
            if (not self._running): return 1
            return None
            
        # start processing
        used = []
        self._resultIm = imagePuzzle(self._im, self._tileSize.get_value(), self._puzzleSize.get_value(), files, used, self._noDouble.get_active(), _updateCall, self)
        
        # set result
        if self._resultIm:
            self._labelResultDim.set_text("%i x %i" % self._resultIm.size)
            try:
                im = ImageHelper.FitResize(self._resultIm, (320, 240))
                pixbuf = ImageHelper.GetGtkPixbuf(im)
                self._previewImage.set_from_pixbuf(pixbuf)
                self._labelStatus.set_text('')
            except:
                self._labelStatus.set_text('Result ok, but can not display as thumbnail')
        else:
            self._labelStatus.set_text('Error while processing')
            
        # lock
        self._running = False
        self._start.set_label('Start')
        pass
    
    def onSave(self, widget):
        if self._resultIm != None:
            fileSave = gtk.FileChooserDialog(title="Save as...", parent=self._window, action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                                                                                                                                    gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
            fileSave.set_filter(self._fileFilter)
            fileSave.set_do_overwrite_confirmation(True)
            fileSave.run()
            saveTarget = fileSave.get_filename()
            fileSave.destroy()
            if (saveTarget):
                self._resultIm.save(saveTarget.decode())


if __name__ == '__main__':
    imagePuzzle = GtkImagePuzzle()
    imagePuzzle.show()
    pass
